import React, { useState, useEffect } from 'react';

import { NavBar, Icon, List, ImagePicker, Picker, DatePicker, TextareaItem, Button, Toast, Accordion, Modal, InputItem } from 'antd-mobile';

import { R, sexList, regionList, MAX_LENGTH_PHOTO } from "@/assets/js/dict"
import { uploadPict, previewPict,deleteFile } from "@/api/login.js";

import { getParentDetails, postParentUpdate } from '@/api/parent/parent.js'

import './userInfo.scss';

import { createForm } from 'rc-form'

var reImgObj = []; // 图片 imgObj
var reId = []; // 图片 id

function UpdataUserInfoParent (props) {
    const [userInfoDetailsObject, setUserInfoDetailsObject] = useState({})
    const [userInfoDetailsObjectRule, SetUserInfoDetailsObjectRule] = useState({}); // 个人信息 错误信息
    const [photo, setPhoto] = useState([]); // 头像照片
    const { getFieldProps } = props.form;



    /**
    * 压缩图片
    *@param img 被压缩的img对象
    * @param type 压缩后转换的文件类型
    * @param mx 触发压缩的图片最大宽度限制
    * @param mh 触发压缩的图片最大高度限制
    */
    function compressImg (img, type, mx, mh) {
        return new Promise((resolve, reject) => {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            const { width: originWidth, height: originHeight } = img;
            // 最大尺寸限制
            const maxWidth = mx;
            const maxHeight = mh;
            // 目标尺寸
            let targetWidth = originWidth;
            let targetHeight = originHeight;
            if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > 1) {
                    // 宽图片
                    targetWidth = maxWidth;
                    targetHeight = Math.round(maxWidth * (originHeight / originWidth))
                } else {
                    // 高图片
                    targetHeight = maxHeight;
                    targetWidth = Math.round(maxHeight * (originWidth / originHeight))
                }
            }
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            context.clearRect(0, 0, targetWidth, targetHeight);
            // 图片绘制
            context.drawImage(img, 0, 0, targetWidth, targetHeight);
            canvas.toBlob(function (blob) {
                resolve(blob)
            }, type || 'image/png')
        })
    }

    // 压缩前将file转换成img对象
    function readImg (file) {
        return new Promise((resolve, reject) => {
            const img = new Image()
            const reader = new FileReader()
            reader.onload = function (e) {
                img.src = e.target.result
            }
            reader.onerror = function (e) {
                reject(e)
            }
            reader.readAsDataURL(file)
            img.onload = function () {
                resolve(img)
            }
            img.onerror = function (e) {
                reject(e)
            }
        })
    }

    const compress = async function (file, type, mx = 1000, mh = 1000) {
        const img = await readImg(file);
        let blob = await compressImg(img, file.type, mx, mh);
        return blob;
    };

    // 上传头像
    let onChangePhoto = async function (files, type, code) {
        console.log(files, type, code);
        if (type === "add") {
            if (files.length > 0) {
                let f = files[0].file;
                if (f.size >= MAX_LENGTH_PHOTO) {
                    Toast.info("请选择小于6兆的图片");
                    setPhoto([]);
                } else {
                    try {
                        const blob = await compress(f, f.type, 1000, 1000);
                        console.log("b----------->", blob);
                        f = blob;
                    } catch (e) {
                        console.error("error 压缩图片异常---> ", e);
                    }
                    uploadPict({ file: f, note: "用户头像" }, (res) => {
                        if (res[R.code] === R.success) {
                            let rePhoto = [{ file_id: res[R.data], url: previewPict(res[R.data]) }];
                            console.log("re---> ", rePhoto);
                            setPhoto(rePhoto);
                        }
                    });
                }
            }
        } else if(type === "remove"){
            deleteFile({
                id: photo[0].file_id
            }).then(res=>{
                if(res.code === '000000'){
                    setPhoto([...files]);
                }
            })
        } else{
            setPhoto([]);
        }
    }

    // 保存个人信息修改
    function handleSaveUpdataUserInfo () {
        let postData = {};
        postData = props.form.getFieldsValue().userInfoDetailsObject;
        postData.id = JSON.parse(sessionStorage.getItem('userInfo')).id;
        postData.photo = photo.length ? photo[0].file_id : '';
        postData.gender = postData.gender[0]; // 性别
        postData.region = postData.region[0]; // 居住区域

        console.log('post --->>>', postData);

        postParentUpdate(postData).then(res => {
            if (res.code == '000000') {
                Toast.success('个人信息修改成功', 1, () => {
                    props.history.goBack();
                });
            }
        }).catch(err => {

        })

    }

    useEffect(() => {
        // 查看家长个人信息 GET
        let postData = {};
        postData.parent_id = JSON.parse(sessionStorage.getItem('userInfo')).id;

        getParentDetails(postData).then(res => {
            if (res.code == '000000') {
                console.log('res -------->>>', res);
                setUserInfoDetailsObject(res.responseData)
                if (res.responseData.photo) {
                    let imgFileObj = [];
                    res.responseData.photo.split(',').map(item => {
                        imgFileObj.push({
                            file_id: item,
                            url: previewPict(item)
                        })
                    })
                    setPhoto(imgFileObj);
                }
            }
        }).catch(err => {

        })
    }, [])

    return (
        <div className="parent-details">
            <div className="page-title  parent-tit">
                <NavBar
                    mode="light"
                    icon={<Icon type="left" />}
                    onLeftClick={() => {
                        props.history.goBack()
                    }}
                    key="1"
                >
                    个人信息
                </NavBar>

            </div>
            <div className="page-content parent-content">
                <div className="parent-content-piece">
                    <div className="form-box">
                        <div className="form-tit">
                            <i className="mini-block"></i>
                            <strong>基本信息</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <Picker
                                    data={sexList}
                                    cols={1}
                                    error={userInfoDetailsObjectRule.gender}
                                    onErrorClick={() => {
                                        Modal.alert(userInfoDetailsObjectRule.gender)
                                    }}
                                    {...getFieldProps('userInfoDetailsObject.gender', {
                                        initialValue: [userInfoDetailsObject.gender]
                                    })}

                                >
                                    <List.Item arrow="horizontal">性別</List.Item>
                                </Picker>
                                <Picker
                                    data={regionList}
                                    title="居住区域"
                                    cols={1}
                                    error={userInfoDetailsObjectRule.region}

                                    {...getFieldProps('userInfoDetailsObject.region', { initialValue: [userInfoDetailsObject.region] })}

                                >
                                    <List.Item arrow="horizontal">居住区域</List.Item>
                                </Picker>

                                <TextareaItem
                                    {...getFieldProps('userInfoDetailsObject.site', {
                                        initialValue: userInfoDetailsObject.site
                                    })}
                                    title="地址"
                                    placeholder="请输入详细地址(需要具体到小区名)"
                                    clear
                                    error={userInfoDetailsObjectRule.site}
                                    onErrorClick={() => {
                                        Modal.alert(userInfoDetailsObjectRule.site)
                                    }}
                                    autoHeight
                                />

                                <List.Item>
                                    用户头像
                                    <List.Item.Brief>
                                        <ImagePicker
                                            files={photo}
                                            onChange={onChangePhoto}
                                            onImageClick={(index, fs) => console.log(index, fs)}
                                            selectable={photo.length < 1}
                                            multiple={false}
                                            accept="image/jpeg,image/jpg,image/png"
                                        />
                                    </List.Item.Brief>
                                </List.Item>
                            </List>
                        </div>

                        <Button type="primary" onClick={handleSaveUpdataUserInfo}>保存修改</Button>
                    </div>
                </div>
            </div>


        </div >
    );
}

UpdataUserInfoParent = createForm()(UpdataUserInfoParent);

export default UpdataUserInfoParent;